package com.baosight.sczx.zm.cp.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.User;
import com.baosight.sczx.common.zm.cInterface.cs.Engineering;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlan;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlanCM;
import com.baosight.sczx.zm.cp.domain.ZMCPProfessionalPlan;

/**
 * <p>Title: ServiceZMCP01.java</p>
 * <p>Description: 采煤专业计划主表</p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author高总
 * @version 1.0
 * <pre>Histroy:
 *          2011-10-21 下午03:27:32 高总  Create
 *</pre>
 */
public class ServiceZMCP01  extends ServiceEPBase {
	
	/**
	 * <p>Function: initLoad</p>
	 * <p>Description: 初始化</p>
	 * <p>return value: ServiceZMCP01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-21下午03:26:45高总
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		EiInfo outInfo=new EiInfo();
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
//		EiInfo outInfo = this.query(inInfo);
		outInfo.addBlock(Department.getInstance().getConstructionUnit("cmes.cp.department", "orgCode", "orgName", false));		
//		outInfo.set("fdCreatorId", UserSession.getUserId());//登录人的默认值
//		outInfo.set("fdCreator", UserSession.getInSessionProperty("UserCname"));
//		outInfo.set("fdCreateDepartmentId", UserSession.getInSessionProperty("orgCode"));//单位的默认值		
//		outInfo.set("fdCreateDepartment", UserSession.getInSessionProperty("orgName"));//单位的默认值
		outInfo.addBlock("result").setBlockMeta(new ZMCPProfessionalPlan().eiMetadata);
	    outInfo.addBlock("detail").setBlockMeta(new ZMCPProducePlanCM().eiMetadata);
	    
		outInfo.addBlock(Engineering.getEngineeringForCM("cmes.cp.engineering", "0", "", "1", false));
		outInfo.addBlock(Department.getInstance().getConstructionUnit("cmes.cp.department", "orgCode", "orgName", false));
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.coalType", true));//采煤方法
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.recoveryProcess", true));//采煤方式
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.conditon", true));//生产条件
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.coalKind", true));//煤种
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.qualityGrade", true));//质量等级
		return outInfo;
	}
	
	/**
	 * <p>Function: query</p>
	 * <p>Description: 查询</p>
	 * <p>return value: ServiceZMCP01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-21下午03:26:59高总
	 * </p>
	 *
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		StaticTools.setQueryParameters(inInfo, "fdPlanType", "采煤计划", true);
		//StaticTools.setQueryParameters(inInfo, "fdCreateDepartmentId", UserSession.getInSessionProperty("orgCode"), true);
		EiInfo outInfo = super.query(inInfo, "ZMCPProfessionalPlan.query", new ZMCPProfessionalPlan());
		outInfo.addBlock("detail").setBlockMeta(new ZMCPProducePlanCM().eiMetadata);
		return outInfo;
	}	
	
	/**
	 * <p>Function: insert</p>
	 * <p>Description: 新增</p>
	 * <p>return value: ServiceZMCP01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-21下午03:31:06高总
	 * </p>
	 *
	 */
	@Override	
	public EiInfo insert(EiInfo inInfo) {
		//校验是否重复
		Map<String, String>	params = new HashMap<String, String>();
		params.put("fdPlanType", inInfo.getBlock("result").getCellStr(0, "fdPlanType"));
		params.put("fdPlanYear", inInfo.getBlock("result").getCellStr(0, "fdPlanYear"));
		params.put("fdPlanMonth", inInfo.getBlock("result").getCellStr(0, "fdPlanMonth"));
		boolean validate = this.validate(inInfo, "ZMCPProfessionalPlan.validate", params, "insert");
		
		if(validate) {
			return inInfo;
		}
		else {
			inInfo.getBlock("result").setCell(0, "fdCreatorId",  UserSession.getUserId());
			inInfo.getBlock("result").setCell(0, "fdCreator", UserSession.getInSessionProperty("UserCname"));
			inInfo.getBlock("result").setCell(0, "fdCreateDepartmentId",UserSession.getInSessionProperty("orgCode"));
			inInfo.getBlock("result").setCell(0, "fdCreateDepartment", UserSession.getInSessionProperty("orgName"));
			inInfo.getBlock("result").setCell(0, "fdKeyId", TablePk.getInstance().getNextValue("T_CP_PROFESSIONALPLAN"));
			EiInfo outinfo = super.insert(inInfo, "ZMCPProfessionalPlan.insert");
			return outinfo;
		}
	}
	
	/**
	 * <p>Function: update</p>
	 * <p>Description: 修改</p>
	 * <p>return value: ServiceZMCP01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-21下午04:59:23高总
	 * </p>
	 *
	 */
	@Override
	public EiInfo update(EiInfo inInfo) {		
		EiInfo outInfo = super.update(inInfo, "ZMCPProfessionalPlan.update");
		return outInfo;
	}	
	
	/**
	 * <p>Function: delete</p>
	 * <p>Description: 删除</p>
	 * <p>return value: ServiceZMCP01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-21下午04:12:10高总
	 * </p>
	 *
	 */
	@Override
	public EiInfo delete(EiInfo inInfo) {
		//判断是否有明细
		Map<String, String>	params = new HashMap<String, String>();
		params.put("fdProfessionalplanId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		boolean validate = this.validate(inInfo, "ZMCPProducePlanCM.validate", params, "delete");
		
		if(validate) {
			return inInfo;
		}
		else {
			EiInfo _temp = super.delete(inInfo, "ZMCPProfessionalPlan.delete");
			EiInfo outInfo = this.query(inInfo);
			outInfo.setMsg(_temp.getMsg());
			outInfo.setDetailMsg(_temp.getDetailMsg());
			return outInfo;
		}
	}	
	
	/**
	 * <p>Function: report</p>
	 * <p>Description: 上报</p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-22上午10:59:40高总
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo report(EiInfo inInfo) {
		EiInfo produceInfo = new EiInfo();
		produceInfo.addBlock("result").addBlockMeta(new ZMCPProducePlan().eiMetadata);
		produceInfo.addBlock("updateResult").addBlockMeta(new ZMCPProducePlan().eiMetadata);
		int j=0,h=0;
		for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
		{
			String fdPlanYear = inInfo.getBlock("result").getCellStr(i, "fdPlanYear");
			String fdPlanMonth = inInfo.getBlock("result").getCellStr(i, "fdPlanMonth");
			
			//判断是否有明细
			Map map = new HashMap();
			map.put("fdProfessionalplanId", inInfo.getBlock("result").getCellStr(i, "fdKeyId"));
			List<ZMCPProducePlanCM> list = dao.query("ZMCPProducePlanCM.query", map);
			if(list.size()>0)
			{	
				//查询是否已经有当月的草拟或生效的生产计划主表
				Map<String, String> params = new HashMap<String, String>();
				params.put("fdPlanYear", fdPlanYear);
				params.put("fdPlanMonth", fdPlanMonth);
				List<ZMCPProducePlan> _result = dao.query("ZMCPProducePlan.validate", params);
				
				String fdProduceId = TablePk.getInstance().getNextValue("T_CP_PRODUCEPLAN");
				//如果生产计划主表记录不存在，则生成一条记录
				if(_result != null && _result.isEmpty()){
					//查询年计划分解量
					Map map1 = new HashMap();
					map1.put("fdPlanYear", fdPlanYear);
					map1.put("fdPlanStatus", "生效");
					List<ZMCPProducePlan> list1 = dao.query("ZMCPProducePlan.query", map1);
					if(list1.size()>0)
					{
						produceInfo.getBlock("result").setCell(j, "fdDecomposeMine", list1.get(0).getFdDecomposeMine());
						produceInfo.getBlock("result").setCell(j, "fdDecomposeGrubMine", list1.get(0).getFdDecomposeGrubMine());
						produceInfo.getBlock("result").setCell(j, "fdDecomposeGrub", list1.get(0).getFdDecomposeGrub());
						produceInfo.getBlock("result").setCell(j, "fdDecomposeDeploitation", list1.get(0).getFdDecomposeDeploitation());
					}
					produceInfo.getBlock("result").setCell(j, "fdKeyId", fdProduceId);
					produceInfo.getBlock("result").setCell(j, "fdTitle", fdPlanYear+"年"+fdPlanMonth+"月的生产计划");
					produceInfo.getBlock("result").setCell(j, "fdPlanYear", fdPlanYear);
					produceInfo.getBlock("result").setCell(j, "fdPlanMonth", fdPlanMonth);
					produceInfo.getBlock("result").setCell(j, "fdPlanMine", 0);
					produceInfo.getBlock("result").setCell(j, "fdPlanGrub", 0);
					produceInfo.getBlock("result").setCell(j, "fdPlanDeploitation", 0);
					produceInfo.getBlock("result").setCell(j, "fdPlanProjectNum", 0);
					produceInfo.getBlock("result").setCell(j, "fdMineUnit", "吨");
					produceInfo.getBlock("result").setCell(j, "fdGrubUnit", "米");
					produceInfo.getBlock("result").setCell(j, "fdDeploitationUnit", "米");
					produceInfo.getBlock("result").setCell(j, "fdPlanStatus", "草拟");
					produceInfo.getBlock("result").setCell(j, "fdPlanSource", "1");
					produceInfo.getBlock("result").setCell(j, "fdEditor", UserSession.getInSessionProperty("UserCname"));
					produceInfo.getBlock("result").setCell(j, "fdEditDate", StaticTools.getDate());
					j++;					
				}
				else
				{
					if("草拟".equals(_result.get(0).getFdPlanStatus()))
					{
						fdProduceId = _result.get(0).getFdKeyId();
						if(_result.get(0).getFdPlanSource()==0)
						{
							produceInfo.getBlock("updateResult").setCell(h, "fdKeyId", fdProduceId);
							h++;
						}		
					}
					else
					{
						inInfo.setStatus(-1);
						inInfo.setMsg("已经存在有效的该年月生产计划，不能再上报了！");
						return inInfo;
					}		
				}
				//添加生产计划主键
				inInfo.getBlock("result").setCell(i, "fdProduceplanId", fdProduceId);
			}
			else
			{
				inInfo.setStatus(-1);
				inInfo.setMsg("上报的专业计划中有的没有明细，请添加明细后上报！");
				return inInfo;
			}
			//上报时要记录发布人
			inInfo.getBlock("result").setCell(i, "fdPulisherId", UserSession.getUserId());
			inInfo.getBlock("result").setCell(i, "fdPulisher", UserSession.getInSessionProperty("UserCname"));
		}
		super.update(inInfo, "ZMCPProfessionalPlan.report");//更改专业计划主表状态为上报
		super.insert(produceInfo, "ZMCPProducePlan.insert");//若没有生产计划主表，新增一条
		super.update(produceInfo, "ZMCPProducePlan.updatePlanSource", "updateResult");//若存在生产计划主表，并且计划来源为0-"新增"，则更改计划来源为2-"混合"
		super.update(inInfo, "ZMCPProducePlanCM.updateProduceplanId");//回填明细表的生产计划ID
		super.update(inInfo,"ZMCPProducePlanCM.updateProduceplanSum");//计算生产计划主表中的统计值
		EiInfo outInfo = this.query(inInfo);
		return outInfo;
	}	
	
	/**
	 * <p>Function: validate</p>
	 * <p>Description: 对主表记录新增，删除，上报前的后台校验</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-21下午03:40:23高总
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params, String type) {
		if(params == null) {
			params = new HashMap<String, String>();
		}

		List result = dao.query(sqlName, params);
		if(result != null && result.size() > 0 && !"report".equals(type)) {
			if(type.equals("insert")){
				String msg = "该年月的采煤专业计划已经存在！";
				inInfo.setMsg(msg);
			}
			else if(type.equals("delete")){
				String msg = "该采煤专业计划包含详细计划，不可删除！";
				inInfo.setMsg(msg);
			}
			inInfo.setStatus(-1);
			return true;
		}		
		return false;
	}
	
}
